package com.shopcart.servlet;

import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopcart.controller.CustomerController;
import com.shopcart.entity.Customer;
import com.shopcart.exception.CustomerExistsException;

@WebServlet(name="RegisterServlet", urlPatterns={"/register"})
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public RegisterServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException,
			IOException {
		CustomerController cc = null;
		try {
			Context ctx = new InitialContext();
			cc = (CustomerController) ctx
					.lookup("ejb/CustomerControllerBean");
		} catch (NamingException e) {
			System.err.println("Error getting bean!");
			e.printStackTrace();
		}

		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String email = request.getParameter("email");
		String password = request.getParameter("password");

		try {
			Customer c = cc.registerCustomer(email, password,
					firstName, lastName);
			c.setLogin(true);
			HttpSession session = request.getSession();
			session.setAttribute("customer", c);
			request.getRequestDispatcher("login.jsp").forward(
					request, response);
			return;
		} catch (CustomerExistsException e) {
			System.out.println("Duplicate user error : " + email
					+ " exists in the system");
		}
		request.getRequestDispatcher("register.jsp").forward(request,
				response);
	}
}